#include "MessageHandler.h"
#include <sstream>

MessageHandler::Message MessageHandler::parseMessage(const string &rawMessage)
{
    Message msg;
    // 格式: TYPE|SENDER|RECEIVER|CONTENT
    size_t pos1 = rawMessage.find('|');
    size_t pos2 = rawMessage.find('|', pos1 + 1);
    size_t pos3 = rawMessage.find('|', pos2 + 1);

    if (pos1 != string::npos && pos2 != string::npos && pos3 != string::npos)
    {
        string typeStr = rawMessage.substr(0, pos1);
        msg.sender = rawMessage.substr(pos1 + 1, pos2 - pos1 - 1);
        msg.receiver = rawMessage.substr(pos2 + 1, pos3 - pos2 - 1);
        msg.content = rawMessage.substr(pos3 + 1);

        if (typeStr == "LOGIN")
            msg.type = LOGIN;
        else if (typeStr == "LOGOUT")
            msg.type = LOGOUT;
        else if (typeStr == "PRIVATE")
            msg.type = PRIVATE_MSG;
        else if (typeStr == "BROADCAST")
            msg.type = BROADCAST_MSG;
        else
            msg.type = ERROR;
    }
    else
    {
        msg.type = ERROR;
    }
    return msg;
}

string MessageHandler::formatMessage(MessageType type, const string &sender,
                                     const string &receiver, const string &content)
{
    string typeStr;
    switch (type)
    {
    case LOGIN:
        typeStr = "LOGIN";
        break;
    case LOGOUT:
        typeStr = "LOGOUT";
        break;
    case PRIVATE_MSG:
        typeStr = "PRIVATE";
        break;
    case BROADCAST_MSG:
        typeStr = "BROADCAST";
        break;
    case ERROR:
        typeStr = "ERROR";
        break;
    }
    return typeStr + "|" + sender + "|" + receiver + "|" + content;
}